#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：BroadviewCoss
@File    ：send_feishu_msg.py
@IDE     ：PyCharm
@Author  ：kdly
@Date    ：2025/4/2 下午4:57
'''
import time
import json
import hmac
import base64
import hashlib
import requests
import logging

logger = logging.getLogger()
# 修改权限
logger.setLevel(logging.INFO)


def gen_sign(timestamp, secret):
    # 拼接timestamp和secret
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
    # 对结果进行base64处理
    sign = base64.b64encode(hmac_code).decode('utf-8')
    return sign


def send_feishu_message(webhook_url, sign, alert_data):
    """
    向飞书群机器人发送消息
    :param webhook_url: 飞书群机器人的Webhook地址
    :param sign: 飞书群机器人的签名
    :param alert_data: 要发送的消息内容 alert_data = {
        "group": "测试组",
        "type": "进程监控",
        "name": "test",
        "obj": "nginx",
        "hostname": "127.0.0.1",
        "status": 0,
        "error": "Probe failed",
        "start_time": "2025-04-02 16:27:28",
        "end_time": "2025-04-02 16:30:13"
    }
    :return: API响应内容
    """
    # 构建消息内容
    if alert_data['status'] == 0:
        content = """**BroadviewCoss告警信息**\n"""
    else:
        content = """**BroadviewCoss告警恢复**\n"""

    content += f"""监控分组: {alert_data['group']}
监控类型: {alert_data['type']}
监控名称: {alert_data['name']}
监控对象: {alert_data['obj']}"""

    if alert_data['status'] == 0:
        if alert_data['hostname']:
            content += f"""
监控主机: {alert_data['hostname']}
详细信息: {alert_data['error']}
故障时间: {alert_data['start_time']}"""
        else:
            content += f"""
详细信息: {alert_data['error']}
故障时间: {alert_data['start_time']}"""

    else:
        if alert_data['hostname']:
            content += f"""
监控主机: {alert_data['hostname']}
详细信息: {alert_data['error']}
故障时间: {alert_data['start_time']}
恢复时间: {alert_data['end_time']}"""

        else:
            content += f"""
详细信息: {alert_data['error']}
故障时间: {alert_data['start_time']}
恢复时间: {alert_data['end_time']}"""

    timestamp = int(time.time())  # 返回浮点数形式的秒级时间戳（含小数部分）,转换为10位整数秒级时间戳
    sign = gen_sign(timestamp, sign)

    # 构建消息卡片
    payload = {
        "timestamp": timestamp,  # 时间戳。
        "sign": sign,  # 得到的签名字符串。
        "msg_type": "interactive",
        "card": {
            "schema": "2.0",
            "config": {
                "update_multi": True,
                "style": {
                    "text_size": {
                        "normal_v2": {
                            "default": "normal",
                            "pc": "normal",
                            "mobile": "heading"
                        }
                    }
                }
            },
            "body": {
                "direction": "vertical",
                "padding": "12px 12px 12px 12px",
                "elements": [
                    {
                        "tag": "markdown",
                        "content": content,
                        "text_align": "left",
                        "text_size": "normal_v2",
                        "margin": "0px 0px 0px 0px"
                    },
                    {
                        "tag": "markdown",
                        "content": "---",
                        "text_align": "left",
                        "text_size": "normal_v4",
                        "margin": "0px 0px 0px 0px"
                    },
                    {
                        "tag": "markdown",
                        "content": "BroadviewCoss告警信息",
                        "text_align": "left",
                        "text_size": "normal_v4",
                        "margin": "0px 0px 0px 0px"
                    },
                ]
            },
            "header": {
                "title": {
                    "tag": "plain_text",
                    "content": "BroadviewCoss 告警通知"
                },
                "subtitle": {
                    "tag": "plain_text",
                    "content": ""
                },
                "template": "green" if alert_data['status'] == 1 else "red",
                "padding": "12px 12px 12px 12px"
            }
        }
    }
    headers = {
        'Content-Type': 'application/json'
    }

    if not webhook_url:
        return
    try:
        response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
        response.raise_for_status()  # 检查请求是否成功
        logger.info(response.json())
    except requests.exceptions.RequestException as e:
        logger.error(f"发送飞书群告警失败：{str(e)}")
        return False
    return True
